import { handleFileOpen } from '../fn/main';
import { dialog } from 'electron';
const path = require('path');
const fs = require('fs');
import { getFiles } from '../fn/getFiles';

jest.mock('../fn/getFiles');

jest.mock('electron', () => ({
  dialog: {
    showOpenDialog: jest.fn(),
    showMessageBoxSync: jest.fn(),
  },
}));

describe('handleFileOpen', () => {
  const mainWindow = {}; // 模拟 mainWindow 对象

  afterEach(() => {
    jest.clearAllMocks();
  });

  it('should return file paths when method is openFile and type is specified', async () => {
    const config = {
      method: 'openFile',
      type: 'img',
    };

    const filePaths = ['\\path\\to\\file1.jpg', '\\path\\to\\file2.png'];
    dialog.showOpenDialog.mockResolvedValue({ canceled: false, filePaths });

    const files = [
      { name: 'file1.jpg', path: '\\path\\to\\file1.jpg' },
      { name: 'file2.png', path: '\\path\\to\\file2.png' },
    ];

    getFiles.mockResolvedValueOnce(files)
    // jest.spyOn(require('../fn/getFiles'), 'getFiles').mockResolvedValue(files)

    const result = await handleFileOpen(config);

    expect(result).toEqual(files);
  });

  it('should return file path when method is openFile and type is not specified', async () => {
    const config = {
      method: 'openFile',
    };

    const filePath = '/path/to/file.txt';
    dialog.showOpenDialog.mockResolvedValue({ canceled: false, filePaths: [filePath] });

    const result = await handleFileOpen(config);

    expect(result).toEqual(filePath);
  });

  it('should return undefined when dialog is canceled', async () => {
    const config = {
      method: 'openFile',
    };

    dialog.showOpenDialog.mockResolvedValue({ canceled: true });

    const result = await handleFileOpen(config);

    expect(result).toBeUndefined();
  });

  it('should show warning message and return undefined when files exceed the limit', async () => {
    const config = {
      method: 'openFile',
      type: 'img',
    };

    const filePaths = new Array(201).map((v, i) => {
      return `/path/to/file${i}.jpg`
    })
    dialog.showOpenDialog.mockResolvedValue({ canceled: false, filePaths });

    const files = new Array(201).map((v, i) => {
      return {
        name: `file${i}.jpg`,
        path: `/path/to/file${i}.jpg`,
      }
    })

    getFiles.mockResolvedValueOnce(files)

    dialog.showMessageBoxSync.mockReturnValue(0); // 用户选择确定

    const result = await handleFileOpen(config);

    expect(dialog.showMessageBoxSync).toHaveBeenCalledWith(mainWindow, {
      type: 'warning',
      buttons: ['确定'],
      title: '警告',
      message: '单次选的的图片超过上限!',
    });
    expect(result).toBeUndefined();
  });
});